<template>
  <div>
    <el-button class="mb5" style="float: right" type="primary" @click="getList">
      <template #icon>
        <i-ep-search/>
      </template>
      刷新
    </el-button>
    <el-table v-adaptive="520" :border="true" :data="examApplyList" :header-cell-style="$headerCellStyle" :stripe="true"
              highlight-current-row>
      <el-table-column fixed="left" label="明细" type="expand">
        <template #default="props">
          <div m="4">
            <el-table :data="props.row.detailVoList" :stripe="true" highlight-current-row>
              <el-table-column fixed="left" width="50px"/>
              <el-table-column fixed="left" label="项目代码" prop="itemCode" width="120px"/>
              <el-table-column fixed="left" label="项目名称" prop="itemName" width="290px"/>
              <el-table-column fixed="left" label="部位" prop="examPosition" width="190px">
                <template #default="scope">
                  {{ scope.row.examPositionName }}
                </template>
              </el-table-column>
              <el-table-column fixed="left" label="数量" prop="num" width="80px"/>
              <el-table-column fixed="left" label="单价(元)" prop="price" width="110px"/>
              <el-table-column fixed="left" label="总价(元)" prop="sumPrice" width="110px"/>
              <el-table-column :align="'center'" :show-overflow-tooltip="true" class-name="small-padding fixed-width"
                               fixed="right"
                               label="操作" width="70">
                <template #default="scope">
                  <el-tooltip class="item" content="删除" effect="dark" placement="top">
                    <el-button circle type="danger"
                               @click="handleDelete(scope.row,'1')">
                      <template #icon>
                        <i-ep-delete/>
                      </template>
                    </el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </el-table-column>
      <el-table-column v-if="isQuoted" :align="'center'" label="模板主题名称" min-width="150" prop="title">
        <template #default="scope">
          <span class="ys-css">{{ scope.row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="检查类别" prop="examTypeName"/>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="症状" prop="symptom" width="300"/>
      <el-table-column :align="'center'" label="体征" prop="sign" width="300"/>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" class-name="small-padding fixed-width"
                       fixed="right"
                       label="操作" width="70">
        <template #default="scope">
          <el-tooltip v-if="!isQuoted" class="item" content="删除" effect="dark" placement="top">
            <el-button circle type="danger"
                       @click="handleDelete(scope.row,'2')">
              <template #icon>
                <i-ep-delete/>
              </template>
            </el-button>
          </el-tooltip>
          <el-tooltip v-else class="item" content="引用" effect="dark" placement="top">
            <el-button circle type="success"
                       @click="templateQuote(scope.row)">
              <svg-icon icon-class="save"/>
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script lang="ts" setup>
import {useDictStoreHook} from "@/store/modules/dict.ts";
import {delItemIdenticalGroup, getGroupApplyList} from "@/api/patient/templateDetail.ts";

const dictStore = useDictStoreHook();
const dictDataMap = ref(dictStore.isTypeGetData("position_type"));

const emits = defineEmits(['rowClick']);
const props = defineProps({
  orgId: {
    type: String,
    default: ""
  },
  // 是否从引用加载
  isQuoted: {
    type: Boolean,
    default: false
  }
})

const {proxy} = getCurrentInstance() as any;
const queryParamsRef = ref();
const queryParams = ref<any>({
  type: '3',
  orgId: props.orgId,
  // 是否通过分组后的记录id获取明细
  isAddItem: "Y"
});
const examApplyList = ref([]);
const open = ref(false);

function getList() {
  getGroupApplyList(queryParams.value).then((response: any) => {
    examApplyList.value = response.data;
  });
}

/** 删除按钮操作 */
function handleDelete(row, type) {
  ElMessageBox.confirm("是否确认删除？", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      if (!props.isQuoted) {
        const param = {
          itemIdenticalGroup: row.itemIdenticalGroup,
          templateMasterId: row.templateMasterId,
          detailId: row.detailId
        };
        delItemIdenticalGroup(param).then(() => {
          ElMessage.success("删除成功");
          getList();
        });
      } else {
        if (type === '1') {
          // 遍历外层表格数据
          examApplyList.value.forEach((outerRow: any) => {
            if (outerRow.detailVoList) {
              // 找到内层表格中要删除的行的索引
              const index = outerRow.detailVoList.findIndex((detailRow) => detailRow === row);
              if (index > -1) {
                // 从内层表格数据中移除该行
                outerRow.detailVoList.splice(index, 1);
              }
            }
          });
        }
      }
    })
    .catch(() => {
    });
}

/**
 * 执行科室选择
 * @param e
 * @param row
 */
function deptChange(e: any, row: any) {
  row.implementDept = e.deptId;
}


// 定义类型
type PositionType = {
  dictValue: string;
  dictLabel: string;
};

type RowDetail = {
  num: string | number;
  clinicItemId: string | number;
  examType: string | number;
  examTypeName: string;
  itemCode: string;
  itemName: string;
  orgId: string | number;
  price: string | number;
  vsId: string | number;
  examPosition: string;
  symptom: string;
  relevantDiag: string;
  sign: string;
  remarks: string;
};

type ExamClinicCheckObj = {
  amount: number;
  beginTime: null;
  clinicId: string | number;
  clinicItemId: string | number;
  examId: string | number;
  examPosition: string;
  examPositionArray: PositionType[];
  examType: string | number;
  examTypeName: string;
  itemCode: string;
  itemName: string;
  itemType: string | number;
  num: number;
  orgId: string | number;
  price: number;
  totalPrice: number;
  vsId: string | number;
};

/**
 * 引用模板数据
 * @param row - 包含模板明细数据的对象
 */
function templateQuote(row: { detailVoList: RowDetail[] }) {
  const selectedExamList: ExamClinicCheckObj[] = [];
  const positionTypeDict = dictDataMap.value['position_type'] || [];
  row.detailVoList.forEach((detailRow: RowDetail) => {
    const examPositionArr = detailRow.examPosition.split(',');
    // 查找匹配的部位对象
    const examPositionArray = examPositionArr
      .map((positionValue: string) =>
        positionTypeDict.find((item: PositionType) => item.dictValue === positionValue)
      )
      .filter(Boolean) as PositionType[];
    // 创建检查项目对象
    const examClinicCheckObj: ExamClinicCheckObj = {
      amount: Number(detailRow.num),
      beginTime: null,
      clinicId: detailRow.clinicItemId,
      clinicItemId: detailRow.clinicItemId,
      examId: detailRow.examType,
      examPosition: detailRow.examPosition,
      examPositionArray,
      examType: detailRow.examType,
      examTypeName: detailRow.examTypeName,
      itemCode: detailRow.itemCode,
      itemName: detailRow.itemName,
      itemType: detailRow.examType,
      num: 1,
      orgId: detailRow.orgId,
      price: Number(detailRow.price),
      totalPrice: Number(detailRow.price),
      vsId: detailRow.vsId
    };

    selectedExamList.push(examClinicCheckObj);
  });

  const form = {
    examType: row.detailVoList[0].examType,
    isUrgent: 'N',
    symptom: row.detailVoList[0].symptom,
    relevantDiag: row.detailVoList[0].relevantDiag,
    sign: row.detailVoList[0].sign,
    remarks: row.detailVoList[0].remarks
  };

  emits("rowClick", {
    form,
    selectedExamList
  });
}


defineExpose({
  getList
})
</script>

<style scoped>

</style>
